from flask_wtf import FlaskForm
from wtforms import TextAreaField, SubmitField, StringField, PasswordField
from wtforms.validators import DataRequired, Length, EqualTo
from .model import db, UserData
from flask import flash


class PostForm(FlaskForm):
    body = TextAreaField(label="说说你此时此刻的心情吧......", validators=[DataRequired()])
    submit = SubmitField(label="保存")


class RegisterForm(FlaskForm):
    name = StringField(label="用户名", validators=[DataRequired()])
    passwd = PasswordField(label="密码", validators=[DataRequired(), Length(2, 10)])
    confirm = PasswordField(label="确认密码", validators=[EqualTo("passwd")])
    submit = SubmitField(label="提交")

    def handle(self):
        if self.validate_on_submit():
            user_q = UserData.query.filter_by(name=self.name.data).filter_by(passwd=self.passwd.data).first()
            if user_q:
                flash(f"用户名已存在，请换一个名字")
                return False
            else:
                flash(f"创建成功，用户名是{self.name.data}")
                user_new = UserData(name=self.name.data, passwd=self.passwd.data)
                db.session.add(user_new)
                db.session.commit()
                return True
        else:
            return False

